<template>
    <div class="file-manage">
        <div class="query-form">
            <el-form ref="form" :inline="true" :model="queryForm">
                <el-form-item label="文件名称" prop="fileName">
                    <el-input v-model="queryForm.fileName" placeholder="请输入文件名称" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery">查询</el-button>
                    <el-button @click="handleReset('form')">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="base-table">
            <div class="action">
                <el-upload class="upload-bpmn" action="void" :http-request="uploadFile" :multiple="false"
                    ref="upload" :show-file-list="false" :auto-upload="true">
                    <el-button type="primary">上传文件</el-button>
                </el-upload>
                <el-button type="danger" @click="handlePatchDelete">批量删除</el-button>
            </div>
            <el-table :data="fileList" @selection-change="handleSelectionChange" border cell-style="padding: 4px 0"
                max-height="600">
                <el-table-column type="selection" width="40" align="center" />
                <el-table-column v-for="item in columns" :key="item.prop" :prop="item.prop" :label="item.label"
                    :width="item.width" :formatter="item.formatter" :show-overflow-tooltip="item.overflow" align="center" />
                <el-table-column label="操作" width="250" align="center">
                    <template #default="scope">
                        <el-button size="mini" type="warning" @click="handleDownload(scope.row)">下载</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination class="pagination" background layout="prev, pager, next" :total="pager.totalCount"
                :page-size="pager.pageSize" @current-change="handleCurrentChange" />
        </div>
        <el-dialog :title="action == 'upload' ? '上传进度' : '下载进度'" v-model="showProgress" :close-on-click-modal="false"
            :show-close="false" width="450px" center>
            <el-progress :text-inside="true" :stroke-width="24" :percentage="upLoadProgress" status="success"></el-progress>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleProgressClose">关闭</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { getCurrentInstance, onMounted, reactive, ref, toRaw } from 'vue'
import axios from 'axios'
import utils from "../utils/utils";
export default {
    name: 'file',
    setup() {
        //获取Composition API上下文对象
        const { ctx, proxy } = getCurrentInstance();
        //初始化文件表单对象
        const queryForm = reactive({});
        //初始化文件列表数据
        const fileList = ref([]);
        //初始化分页对象
        const pager = reactive({
            pageNum: 1,
            pageSize: 10
        });
        //选中文件列表的对象
        const checkedfileIds = ref([]);
        //新增文件表单对象
        const fileForm = reactive({});
        //部门列表
        const groupList = ref([]);
        //控制进度显示对象
        const showProgress = ref(false);
        //上传进度
        const upLoadProgress = ref('');
        //定义用户操作行为
        const action = ref('upload');
        //定义动态表格格式
        const columns = reactive([
            {
                label: "文件名称",
                prop: "fileName"
            },
            {
                label: "文件大小",
                prop: "fileSize",
                width:"100"
            },
            {
                label: "文件地址",
                prop: "fileUrl",
                overflow: true
            },
            {
                label: "创建时间",
                prop: "createTime",
                formatter(row, column, value) {
                    return utils.formateDate(new Date(value));
                },
            }
        ]);
        //初始化接口调用
        onMounted(() => {
            getFileList();
        })
        // 获取文件列表
        const getFileList = async () => {
            let params = { ...queryForm, ...pager };
            try {
                const { list, total } = await proxy.$api.getFileList(params);
                fileList.value = list;
                pager.totalCount = total;
            } catch (error) {
                console.log(proxy.$api);
            }
        };
        //查询事件，获取文件列表
        const handleQuery = () => {
            getFileList();
        }
        // 重置查询表单
        const handleReset = (form) => {
            proxy.$refs[form].resetFields();
            getFileList();
        };
        // 分页事件处理
        const handleCurrentChange = (current) => {
            pager.pageNum = current;
            getFileList();
        };
        //文件单个删除
        const handleDelete = async (row) => {
            await proxy.$api.deleteFileByObjectName({
                objectName: row.objectName
            })
            proxy.$message.success('删除成功');
            getFileList();
        }
        //批量删除
        const handlePatchDelete = async () => {
            if (checkedfileIds.value.length == 0) {
                proxy.$message.error('请选择要删除的文件');
                return;
            }
            const res = await proxy.$api.fileDelete({
                fileIds: checkedfileIds.value
            })
            if (res.rows > 0) {
                proxy.$message.success('删除成功');
                getFileList();
            } else {
                proxy.$message.error('删除失败');
            }

        }
        //表格多选
        const handleSelectionChange = (list) => {
            let arr = [];
            list.map(item => {
                arr.push(item.fileId);
            })
            checkedfileIds.value = arr;
        }
        //上传文件直传
        const uploadFile = async (file) => {
            const { uploadUrl } = await proxy.$api.getUploadUrl({ fileName: file.file.name, fileSize: file.file.size, fileType:"1" });
            await axios.request({
                url: uploadUrl,
                method: 'PUT',
                data: file.file,
                headers: { 'Content-Type': 'application/octet-stream' },
                onUploadProgress: function (progressEvent) {
                    // 对原生进度事件的处理
                    if (progressEvent.lengthComputable) {
                        upLoadProgress.value = Math.round(progressEvent.loaded / progressEvent.total * 100) + ""//实时获取上传进度
                        if (upLoadProgress.value === '100') {
                            // showProgress.value = false;
                        } else {
                            action.value = "upload";
                            showProgress.value = true;
                        }
                    }
                }
            })
            getFileList();
        };

        //文件下载
        const handleDownload = (row) => {
            proxy.$nextTick(async () => {
                try {
                    const { downloadUrl } = await proxy.$api.getDownloadUrl({ objectName: row.objectName });
                    const file = await axios.request({
                        url: downloadUrl,
                        method: 'GET',
                        responseType: 'blob',
                        onDownloadProgress: function (progressEvent) {
                            // 对原生进度事件的处理
                            if (progressEvent.lengthComputable) {
                                upLoadProgress.value = Math.round(progressEvent.loaded / progressEvent.total * 100) + ""//实时获取下载进度
                                if (upLoadProgress.value === '100') {
                                    // showProgress.value = false;
                                } else {
                                    action.value = "download";
                                    showProgress.value = true;
                                }
                            }
                        }
                    })
                    console.log(file);
                    const data = file.data;
                    //创建一个Blob对象接收后端传来的文件流
                    const blob = new Blob([data], {
                        type: 'application/octet-stream'
                    })
                    const downloadElement = document.createElement('a')
                    // 创建下载的链接
                    const href = window.URL.createObjectURL(blob)
                    downloadElement.href = href
                    // 下载后文件名
                    downloadElement.download = row.fileName
                    document.body.appendChild(downloadElement)
                    // 点击下载
                    downloadElement.click()
                    // 下载完成移除元素
                    document.body.removeChild(downloadElement)
                    // 释放掉blob对象
                    window.URL.revokeObjectURL(href)
                } catch (error) {
                    console.log(proxy.$api);
                }
            });
        };
        // 上传进度
        const handleProgressClose = () => {
            showProgress.value = false;
        }
        return {
            queryForm,
            fileList,
            columns,
            pager,
            checkedfileIds,
            fileForm,
            groupList,
            showProgress,
            upLoadProgress,
            action,
            getFileList,
            handleQuery,
            handleReset,
            handleCurrentChange,
            handleDelete,
            handlePatchDelete,
            handleSelectionChange,
            uploadFile,
            handleDownload,
            handleProgressClose
        }
    }
}
</script>

<style lang="scss">
.upload-bpmn {
    display: inline-block;
    margin-right: 10px;
}
</style>